//
//  MyInfoViewController.m
//  waiMai
//
//  Created by Haricot_cpc17 on 16/4/12.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MyInfoViewController.h"
//个人中心
@interface MyInfoViewController () <UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UIImageView *headImageView;//头像
@property (nonatomic,strong)UIImagePickerController *myPicker;

@property (nonatomic,strong)UIView *bgView;//查看大头像的背景
@property (nonatomic,strong)UIImageView *imageView;//大头像
@end

@implementation MyInfoViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    //   self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArray = [NSMutableArray arrayWithCapacity:0];
    [self CreateView];
    // Do any additional setup after loading the view.
}
-(void)CreateView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MyInfoID"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UIButton *saveButton = [[UIButton alloc]initWithFrame:CGRectMake(50, HEIGHT - 49 - 230, WIDTH - 100, 40)];
    [saveButton setTitle:@"保存资料" forState:UIControlStateNormal];
    saveButton.layer.cornerRadius = 5;
    saveButton.backgroundColor = UIColorFromRGB(MYBlue);
    [saveButton addTarget:self action:@selector(saveInfo:) forControlEvents:UIControlEventTouchUpInside];
    [_tableView addSubview:saveButton];
}
#pragma mark 保存个人资料的按钮
-(void)saveInfo:(UIButton *)button{
    NSLog(@"保存资料");
}
#pragma mark tableView的代理方法们
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return 2;
    }else{
        return 1;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyInfoID" forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        cell.textLabel.text = @"头像";
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - WIDTH/4, 10, 60 *MYHEIGHT, 60 *MYHEIGHT)];
        _headImageView.layer.cornerRadius = 30 *MYHEIGHT;
        _headImageView.layer.masksToBounds = YES;
        _headImageView.userInteractionEnabled = YES;
        _headImageView.image = [UIImage imageNamed:@"头像"];
        [cell addSubview:_headImageView];
        //给头像添加手势
        UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headImageClick:)];
        [_headImageView addGestureRecognizer:headTap];
        
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"姓名";
            UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(60, 5, WIDTH - 80, 40)];
            textField.backgroundColor = UIColorFromRGB(MYGray);
            [cell addSubview:textField];
        }if (indexPath.row == 1) {
            cell.textLabel.text = @"性别";
            NSArray *buttonArr = @[@"男",@"女"];
            for (int i = 0; i < 2; i++) {
                UILabel *sexLabel = [[UILabel alloc]initWithFrame:CGRectMake(180 + 100 * i, 5, 40, 40)];
                sexLabel.text = [NSString stringWithFormat:@"%@",buttonArr[i]];
                [cell addSubview:sexLabel];
                UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(200 + 100 * i, 10, 30, 30)];
                [button setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateSelected];
                button.backgroundColor = UIColorFromRGB(MYRed);
                button.tag = 300 + i;
                [button addTarget:self action:@selector(sexClick:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:button];
            }
        }
    }
    if (indexPath.section == 2) {
        cell.textLabel.text = @"收货地址";
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(90, 5, WIDTH - 110, 40)];
        textField.backgroundColor = UIColorFromRGB(MYGray);
        [cell addSubview:textField];
    }
    if (indexPath.section == 3) {
        cell.textLabel.text = @"联系电话";
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(90, 5, WIDTH - 110, 40)];
        textField.backgroundColor = UIColorFromRGB(MYGray);
        [cell addSubview:textField];
    }
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)sexClick:(UIButton *)button{
    if (button.tag == 300) {
        NSLog(@"男");
        [button setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        UIButton *but = (id)[self.view viewWithTag:301];
        [but setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
    }
    if (button.tag == 301) {
        NSLog(@"女");
        [button setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        UIButton *but = (id)[self.view viewWithTag:300];
        [but setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        //换头像
        UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //添加Button
        [alertSheet addAction: [UIAlertAction actionWithTitle:@"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            //处理点击拍照
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                _myPicker = [[UIImagePickerController alloc] init];
                _myPicker.delegate = self;
                _myPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                _myPicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                _myPicker.allowsEditing = YES;
                [self presentViewController:_myPicker animated:YES completion:nil];
                NSLog(@"选择相机");
            }else{
                NSLog(@"不支持相机");
            }
        }]];
        [alertSheet addAction: [UIAlertAction actionWithTitle: @"从相册中选取" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            //处理点击从相册选取
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
            {
                NSLog(@"支持图库");
                _myPicker = [[UIImagePickerController alloc] init];
                _myPicker.delegate = self;
                _myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                _myPicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                _myPicker.allowsEditing = YES;
                //[self presentModalViewController:_myPicker animated:YES];
                [self presentViewController:_myPicker animated:YES completion:nil];
                NSLog(@"选择相册");
            }
            //                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
            //                    {
            //                        NSLog(@"支持相片库");
            //                    }
            //                    [self presentViewController:_myPicker animated:YES completion:nil];
        }]];
        [alertSheet addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
        
        [self presentViewController: alertSheet animated: YES completion: nil];
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }else{
        return 50;
    }
}
#pragma mark imagePicker代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //取消选取图片
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"取消选取图片");
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [_myPicker dismissViewControllerAnimated:YES completion:nil];
    
    _headImageView.image = [self fixOrientation:[info objectForKey:UIImagePickerControllerOriginalImage]];
}
#pragma mark 图片横屏
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

#pragma mark 头像的点击手势
-(void)headImageClick:(UITapGestureRecognizer *)tap{
    NSLog(@"点我查看大头像");
    [self showBigImage:@"头像"];
}
#pragma mark 显示大图片
-(void)showBigImage:(NSString *)imageUrl{
    //创建灰色透明背景，使其背后内容不可操作
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    [_bgView setBackgroundColor:[UIColor colorWithRed:0.3
                                                green:0.3
                                                 blue:0.3
                                                alpha:0.7]];
    [self.view addSubview:_bgView];
    
    UITapGestureRecognizer *bgTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bgClick:)];
    [_bgView addGestureRecognizer:bgTap];
    
    //创建边框视图
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH-20, 240)];
    //将图层的边框设置为圆脚
    borderView.layer.cornerRadius = 8;
    borderView.layer.masksToBounds = YES;
    //给图层添加一个有色边框
    borderView.layer.borderWidth = 8;
    borderView.layer.borderColor = [[UIColor colorWithRed:0.9
                                                    green:0.9
                                                     blue:0.9
                                                    alpha:0.7] CGColor];
    [borderView setCenter:_bgView.center];
    [_bgView addSubview:borderView];
    
    //创建关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [closeBtn setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    closeBtn.backgroundColor = [UIColor redColor];
    [closeBtn addTarget:self action:@selector(removeBigImage) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setFrame:CGRectMake(borderView.frame.origin.x+borderView.frame.size.width-20, borderView.frame.origin.y-6, 26, 27)];
    [_bgView addSubview:closeBtn];
    
    //创建显示图像视图
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(borderView.frame)-20, CGRectGetHeight(borderView.frame)-20)];
    _imageView.userInteractionEnabled = NO;
    _imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"头像"]];
    //[_imageView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:LOAD_IMAGE(@"house_moren")];
    [borderView addSubview:_imageView];
    
    //添加捏合手势
    [_imageView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
    
}
-(void)bgClick:(UITapGestureRecognizer *)tap{
    NSLog(@"点击关闭大图");
    [self removeBigImage];
}

//关闭按钮
-(void)removeBigImage
{
    _bgView.hidden = YES;
}

- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
{
    //缩放:设置缩放比例
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;
}


#pragma mark 传递头像给首页的block方法
-(void)returnHeadImage:(ReturnHeadImageBlock)block{
    self.returnHeadImageBlock = block;
}


-(void)viewWillDisappear:(BOOL)animated{
    if (self.returnHeadImageBlock != nil) {
        self.returnHeadImageBlock(_headImageView.image);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
